<template>
  <!-- 页面最外层容器 -->
  <el-container class="configuration-container">
    <!-- 左侧可变宽度面板 -->
    <el-aside class="aside-panel" :style="{ width: asideWidth + 'px' }">
      <div class="aside-content">
        <!-- 配置菜单 -->
        <div class="config-menu">
          <div class="menu-header">
            <span class="menu-title">配置中心</span>
          </div>
          
          <!-- 系统设定 -->
          <div class="menu-item" 
            :class="{ active: activeMenu === 'system' }" 
            @click="selectMenu('system')">
            <el-icon class="menu-icon"><Setting /></el-icon>
            <span class="menu-text">系统设定</span>
            <el-icon class="menu-arrow">
              <ArrowRight v-if="activeMenu !== 'system'" />
              <ArrowDown v-else />
            </el-icon>
          </div>
          
          <!-- 数据项 -->
          <div class="menu-item" 
            :class="{ active: activeMenu === 'data' }" 
            @click="selectMenu('data')">
            <el-icon class="menu-icon"><DataBoard /></el-icon>
            <span class="menu-text">数据项</span>
            <el-icon class="menu-arrow">
              <ArrowRight v-if="activeMenu !== 'data'" />
              <ArrowDown v-else />
            </el-icon>
          </div>
          
          <!-- AI配置 -->
          <div class="menu-item" 
            :class="{ active: activeMenu === 'ai' }" 
            @click="selectMenu('ai')">
            <el-icon class="menu-icon"><Cpu /></el-icon>
            <span class="menu-text">AI配置</span>
            <el-icon class="menu-arrow">
              <ArrowRight v-if="activeMenu !== 'ai'" />
              <ArrowDown v-else />
            </el-icon>
          </div>
          
          <!-- KPI分析配置 -->
          <div class="menu-item" 
            :class="{ active: activeMenu === 'kpi' }" 
            @click="selectMenu('kpi')">
            <el-icon class="menu-icon"><TrendCharts /></el-icon>
            <span class="menu-text">KPI分析配置</span>
            <el-icon class="menu-arrow">
              <ArrowRight v-if="activeMenu !== 'kpi'" />
              <ArrowDown v-else />
            </el-icon>
          </div>
        </div>
      </div>
      
      <div class="aside-footer">
        <el-button type="primary" @click="handleSaveConfiguration">
          <el-icon><Check /></el-icon>
          保存配置
        </el-button>
      </div>
    </el-aside>

    <!-- 分隔条，可拖拽，用于调整asidePanel宽度 -->
    <div class="resizer" @mousedown="startResize"></div>

    <!-- 右侧主面板 -->
    <el-main class="main-panel">
      <div>
        <!-- 顶部标题区域 -->
        <div class="card-header">
          <span class="card-title">系统配置管理</span>
          <div class="header-actions">
            <el-button @click="handleResetConfiguration">
              <el-icon><RefreshLeft /></el-icon>
              重置配置
            </el-button>
            <el-button type="primary" class="idoo-details-add" @click="handleExportConfiguration">
              <el-icon><Download /></el-icon>
              导出配置
            </el-button>
            <el-button type="primary" class="idoo-details-add" @click="handleImportConfiguration">
              <el-icon><Upload /></el-icon>
              导入配置
            </el-button>
          </div>
        </div>
        <el-divider class="custom-divider" />

        <!-- 系统设定内容区域 -->
        <div v-if="activeMenu === 'system'">
          <SystemConfiguration ref="systemConfigRef" />
        </div>

        <!-- 数据项内容区域 -->
        <div v-if="activeMenu === 'data'">
          <DataConfiguration ref="dataConfigRef" />
        </div>

        <!-- AI配置内容区域 -->
        <div v-if="activeMenu === 'ai'">
          <AIConfiguration ref="aiConfigRef" />
        </div>

        <!-- KPI分析配置内容区域 -->
        <div v-if="activeMenu === 'kpi'">
          <KpiConfiguration ref="kpiConfigRef" />
        </div>

        <!-- 默认欢迎页面 -->
        <div v-if="!activeMenu" class="welcome-content">
          <div class="welcome-icon">
            <el-icon size="80"><Setting /></el-icon>
          </div>
          <h2 class="welcome-title">欢迎使用配置中心</h2>
          <p class="welcome-description">
            请选择左侧菜单项开始配置系统参数、数据项或AI模型设置
          </p>
        </div>
      </div>
    </el-main>
  </el-container>

  <!-- 导入配置弹窗 -->
  <el-dialog v-model="showImportDialog" title="导入配置" width="500px">
    <el-upload
      class="upload-demo"
      drag
      action="#"
      :auto-upload="false"
      :on-change="handleFileChange"
      :file-list="fileList"
      accept=".json">
      <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          只能上传 JSON 格式的配置文件
        </div>
      </template>
    </el-upload>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmImport">确认导入</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 全屏loading组件 -->
  <FullScreenLoading 
    :visible="showLoading" 
    :totalDelay="100000" 
    :typingSpeed="200" 
    :messages="['正在保存配置，请稍候...']" 
    :text="loadingText" 
  />
</template>

<script>
import { ref } from 'vue'
import { 
  Setting, 
  DataBoard, 
  Cpu, 
  TrendCharts,
  ArrowRight, 
  ArrowDown, 
  Check, 
  RefreshLeft, 
  Download, 
  Upload,
  UploadFilled
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import FullScreenLoading from '@/idoo-core/loading/streaming-loading/FullScreenLoading.vue'
import SystemConfiguration from '@/components/configuration/SystemConfiguration.vue'
import DataConfiguration from '@/components/configuration/DataConfiguration.vue'
import AIConfiguration from '@/components/configuration/AIConfiguration.vue'
import KpiConfiguration from '@/components/configuration/KpiConfiguration.vue'

export default {
  name: 'Configuration',
  components: {
    Setting,
    DataBoard,
    Cpu,
    TrendCharts,
    ArrowRight,
    ArrowDown,
    Check,
    RefreshLeft,
    Download,
    Upload,
    UploadFilled,
    FullScreenLoading,
    SystemConfiguration,
    DataConfiguration,
    AIConfiguration,
    KpiConfiguration
  },
  setup() {
    // ============== 1. 基础状态 ==============
    
    // 当前激活的菜单
    const activeMenu = ref('')
    
    // 是否显示全屏loading
    const showLoading = ref(false)
    const loadingText = ref('')
    
    // 导入配置弹窗
    const showImportDialog = ref(false)
    const fileList = ref([])
    
    // ============== 2. 可拖拽左侧aside宽度 ==============
    
    // aside 初始宽度
    const asideWidth = ref(280)
    
    // 是否正在拖拽
    const isResizing = ref(false)
    
    // 上一次鼠标坐标，用于计算拖拽距离
    const lastClientX = ref(0)
    
    /**
     * 按下鼠标，开始拖拽
     * @param e
     */
    const startResize = (e) => {
      isResizing.value = true
      lastClientX.value = e.clientX
      document.addEventListener('mousemove', handleResizing)
      document.addEventListener('mouseup', stopResize)
    }
    
    /**
     * 拖拽过程中持续更新 aside 宽度
     * @param e
     */
    const handleResizing = (e) => {
      if (!isResizing.value) return
      const deltaX = e.clientX - lastClientX.value
      asideWidth.value = Math.max(200, asideWidth.value + deltaX)
      lastClientX.value = e.clientX
    }
    
    /**
     * 鼠标松开，结束拖拽
     */
    const stopResize = () => {
      isResizing.value = false
      document.removeEventListener('mousemove', handleResizing)
      document.removeEventListener('mouseup', stopResize)
    }
    
    // ============== 3. 菜单操作 ==============
    
    // 组件引用
    const systemConfigRef = ref(null)
    const dataConfigRef = ref(null)
    const aiConfigRef = ref(null)
    const kpiConfigRef = ref(null)
    
    /**
     * 选择菜单项
     * @param {String} menuKey 菜单键值
     */
    const selectMenu = (menuKey) => {
      activeMenu.value = menuKey
    }
    
    // ============== 4. 配置管理方法 ==============
    
    /**
     * 获取所有配置数据
     */
    const getAllConfigurationData = () => {
      const configData = {
        timestamp: new Date().toISOString(),
        version: '1.0.0'
      }
      
      // 获取系统配置
      if (systemConfigRef.value) {
        configData.systemConfiguration = systemConfigRef.value.getConfigData()
      }
      
      // 获取数据配置
      if (dataConfigRef.value) {
        configData.dataConfiguration = dataConfigRef.value.getConfigData()
      }
      
      // 获取AI配置
      if (aiConfigRef.value) {
        configData.aiConfiguration = aiConfigRef.value.getConfigData()
      }
      
      // 获取KPI配置
      if (kpiConfigRef.value) {
        configData.kpiConfiguration = kpiConfigRef.value.getConfigData()
      }
      
      return configData
    }
    
    /**
     * 加载所有配置数据
     */
    const loadAllConfigurationData = (configData) => {
      try {
        // 加载系统配置
        if (configData.systemConfiguration && systemConfigRef.value) {
          systemConfigRef.value.loadConfigData(configData.systemConfiguration)
        }
        
        // 加载数据配置
        if (configData.dataConfiguration && dataConfigRef.value) {
          dataConfigRef.value.loadConfigData(configData.dataConfiguration)
        }
        
        // 加载AI配置
        if (configData.aiConfiguration && aiConfigRef.value) {
          aiConfigRef.value.loadConfigData(configData.aiConfiguration)
        }
        
        // 加载KPI配置
        if (configData.kpiConfiguration && kpiConfigRef.value) {
          kpiConfigRef.value.loadConfigData(configData.kpiConfiguration)
        }
        
        ElMessage.success('配置加载成功')
      } catch (error) {
        console.error('配置加载失败:', error)
        ElMessage.error('配置加载失败')
      }
    }
    
    /**
     * 验证所有配置
     */
    const validateAllConfigurations = () => {
      const errors = []
      
      // 验证系统配置
      if (systemConfigRef.value) {
        const systemValidation = systemConfigRef.value.validateConfig()
        if (!systemValidation.valid) {
          errors.push(...systemValidation.errors.map(err => `系统配置: ${err}`))
        }
      }
      
      // 验证数据配置
      if (dataConfigRef.value) {
        const dataValidation = dataConfigRef.value.validateConfig()
        if (!dataValidation.valid) {
          errors.push(...dataValidation.errors.map(err => `数据配置: ${err}`))
        }
      }
      
      // 验证AI配置
      if (aiConfigRef.value) {
        const aiValidation = aiConfigRef.value.validateConfig()
        if (!aiValidation.valid) {
          errors.push(...aiValidation.errors.map(err => `AI配置: ${err}`))
        }
      }
      
      // 验证KPI配置
      if (kpiConfigRef.value) {
        const kpiValidation = kpiConfigRef.value.validateConfig()
        if (!kpiValidation.valid) {
          errors.push(...kpiValidation.errors.map(err => `KPI配置: ${err}`))
        }
      }
      
      return {
        valid: errors.length === 0,
        errors
      }
    }
    
    /**
     * 保存配置
     */
    const handleSaveConfiguration = async () => {
      // 先验证配置
      const validation = validateAllConfigurations()
      if (!validation.valid) {
        ElMessage.error('配置验证失败：' + validation.errors.join('；'))
        return
      }
      
      try {
        showLoading.value = true
        loadingText.value = '正在保存配置...'
        
        const configData = getAllConfigurationData()
        console.log('保存的配置数据:', configData)
        
        // 模拟保存API调用
        await new Promise(resolve => setTimeout(resolve, 2000))
        
        ElMessage.success('配置保存成功')
      } catch (error) {
        console.error('配置保存失败:', error)
        ElMessage.error('配置保存失败')
      } finally {
        showLoading.value = false
      }
    }
    
    /**
     * 重置配置
     */
    const handleResetConfiguration = () => {
      ElMessageBox.confirm(
        '此操作将重置所有配置到默认状态，是否继续？',
        '重置确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // 重置各组件配置
        if (systemConfigRef.value) {
          systemConfigRef.value.resetConfig()
        }
        if (dataConfigRef.value) {
          dataConfigRef.value.resetConfig()
        }
        if (aiConfigRef.value) {
          aiConfigRef.value.resetConfig()
        }
        if (kpiConfigRef.value) {
          kpiConfigRef.value.resetConfig()
        }
        
        ElMessage.success('配置重置成功')
      }).catch(() => {
        ElMessage.info('已取消重置')
      })
    }
    
    /**
     * 导出配置
     */
    const handleExportConfiguration = () => {
      try {
        const configData = getAllConfigurationData()
        const dataStr = JSON.stringify(configData, null, 2)
        const dataBlob = new Blob([dataStr], { type: 'application/json' })
        
        const link = document.createElement('a')
        link.href = URL.createObjectURL(dataBlob)
        link.download = `aps-configuration-${new Date().toISOString().split('T')[0]}.json`
        link.click()
        
        ElMessage.success('配置导出成功')
      } catch (error) {
        console.error('配置导出失败:', error)
        ElMessage.error('配置导出失败')
      }
    }
    
    /**
     * 导入配置
     */
    const handleImportConfiguration = () => {
      showImportDialog.value = true
      fileList.value = []
    }
    
    /**
     * 处理文件选择
     */
    const handleFileChange = (file, fileList) => {
      console.log('文件变化:', file, fileList)
    }
    
    /**
     * 确认导入
     */
    const confirmImport = () => {
      if (fileList.value.length === 0) {
        ElMessage.warning('请选择要导入的配置文件')
        return
      }
      
      const file = fileList.value[0].raw
      const reader = new FileReader()
      
      reader.onload = (e) => {
        try {
          const configData = JSON.parse(e.target.result)
          loadAllConfigurationData(configData)
          showImportDialog.value = false
          fileList.value = []
        } catch (error) {
          console.error('配置文件解析失败:', error)
          ElMessage.error('配置文件格式错误')
        }
      }
      
      reader.readAsText(file)
    }
    
    return {
      // 基础状态
      activeMenu,
      showLoading,
      loadingText,
      showImportDialog,
      fileList,
      
      // 拖拽相关
      asideWidth,
      startResize,
      
      // 组件引用
      systemConfigRef,
      dataConfigRef,
      aiConfigRef,
      kpiConfigRef,
      
      // 菜单操作
      selectMenu,
      
      // 配置管理
      getAllConfigurationData,
      loadAllConfigurationData,
      validateAllConfigurations,
      handleSaveConfiguration,
      handleResetConfiguration,
      handleExportConfiguration,
      handleImportConfiguration,
      handleFileChange,
      confirmImport
    }
  }
}
</script>

<style scoped>
.configuration-container {
  height: 87vh;
  display: flex;
}

.aside-panel {
  display: flex;
  flex-direction: column;
  height: calc(90vh - 60px);
  border-right: 1px solid #ebebeb;
}

.aside-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px 15px;
}

.aside-footer {
  text-align: center;
  padding: 15px;
  flex-shrink: 0;
  border-top: 1px solid #ebebeb;
}

.config-menu {
  width: 100%;
}

.menu-header {
  text-align: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #714B67;
}

.menu-title {
  font-size: 18px;
  font-weight: 600;
  color: #714B67;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.menu-item:hover {
  background-color: #f1edf0;
  border-color: #714B67;
}

.menu-item.active {
  background-color: #714B67;
  color: white;
  border-color: #714B67;
}

.menu-icon {
  font-size: 18px;
  margin-right: 12px;
  color: inherit;
}

.menu-text {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
}

.menu-arrow {
  font-size: 14px;
  transition: transform 0.3s ease;
}

.resizer {
  width: 4px;
  cursor: col-resize;
  background-color: #ccc;
  transition: background-color 0.2s;
}

.resizer:hover {
  background-color: #714B67;
}

.main-panel {
  padding: 20px;
  overflow: auto;
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-title {
  color: black;
  font-size: 24px;
  font-weight: 700;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.custom-divider {
  margin: 20px 0;
  border-style: dotted;
}

.welcome-content {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.welcome-icon {
  margin-bottom: 30px;
  color: #714B67;
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  color: #714B67;
  margin-bottom: 20px;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
}

.welcome-description {
  font-size: 16px;
  line-height: 1.6;
  max-width: 500px;
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .configuration-container {
    flex-direction: column;
  }
  
  .aside-panel {
    width: 100% !important;
    height: auto;
    max-height: 300px;
  }
  
  .resizer {
    display: none;
  }
  
  .card-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>

